/*
 * @Author: GY19531 418941369@qq.com
 * @Date: 2022-09-05 14:46:38
 * @LastEditors: GY19531 418941369@qq.com
 * @LastEditTime: 2022-09-06 21:11:49
 * @FilePath: \one-web\src\pages\RemindManage\Component\JoinRemindPeopleLeft.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import ScrollBarLayout from '@/components/ScrollBarLayout';
import {
  AutoComplete,
  Card,
  Col,
  Empty,
  Input,
  message,
  Tooltip,
  Tree,
} from 'antd';
import React, {
  useContext,
  useMemo,
  useState,
  ChangeEvent,
  useCallback,
  useEffect,
} from 'react';
import { SearchOutlined } from '@ant-design/icons';
import '../common/index.less';
import pageStyles from '@/common/pageLayout.less';
import {
  commonDeptGetUser,
  loopArray,
  loopArrayChildren,
  transltateFn,
  uniqueArray,
} from '@/utils';
import { IActionEnum, RemindPeopleContext } from '../common';
import { getUserDataList } from '@/services/BaseLayout';
import MyIcon from '@/components/MyIcon';
type IJoinCopyGiveLeftCard = {
  treeDept: Record<string, any>[];
};
const JoinRemindPeopleLeft: React.FC<IJoinCopyGiveLeftCard> = ({
  treeDept,
}) => {
  const {
    updateDispath,
    leftAutoExpandParent,
    saveUserList,
    leftSelectKeys,
    leftExpandedKeys,
  } = useContext(RemindPeopleContext);

  /**
   * 搜索输入框
   */
  const [leftSearchValue, setLeftSearchValue] = useState<string>('');

  /**
   * 监听改变
   * */
  useEffect(() => {
    let newList: any = [];
    let userList: any[] = saveUserList;
    userList?.forEach((item: any) => {
      let userPositionID: any = item?.userPositionID?.split(',');
      userPositionID?.forEach((itemDept: any) => {
        if (leftSelectKeys?.includes(itemDept)) {
          newList?.push(item);
        }
      });
    });
    let newSet: any = uniqueArray(newList, 'id');
    updateDispath({
      type: IActionEnum.CENTREUSER_ROWS,
      payload: newSet,
    });
  }, [leftSelectKeys, saveUserList]);

  /**
   * 获取用户回调
   * @param res
   */
  const userCallback = (res: any) => {
    if (res && res?.msgFlag) {
      let saveUser: any[] = saveUserList;
      let useList: any[] = [...saveUser, ...res?.rows];
      let newSet: any = uniqueArray(useList, 'id');
      updateDispath({
        type: IActionEnum.SAVE_USER_LIST,
        payload: newSet,
      });
    } else {
      message.error(res?.msg);
    }
  };

  //
  const { getUserRun, getUserLoading } = getUserDataList(userCallback);
  useEffect(() => {
    updateDispath({
      type: IActionEnum.LEFTDEPT_USER_LOADING,
      payload: getUserLoading,
    });
  }, [getUserLoading]);
  /**
   * 搜索下拉菜单
   */
  const autoOptionLeft = useMemo(() => {
    let option: Record<string, any>[] = [];
    const tileTreeData = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        if (item?.children && item?.children?.length > 0) {
          tileTreeData(item?.children);
        }
        const name = item?.text;
        if (name?.includes(leftSearchValue)) {
          const nameLength = name?.length;
          const select = name?.search(leftSearchValue);
          const searchLength = leftSearchValue?.length;
          const afterStr = name?.slice(0, select);
          const selectStr = leftSearchValue;
          const beforeStr = name?.slice(select + searchLength, nameLength);
          option.push({
            value: name,
            key: item?.id,
            label: (
              <div>
                <span>{afterStr}</span>
                <span style={{ color: '#f50' }}>{selectStr}</span>
                <span>{beforeStr}</span>
              </div>
            ),
            itemrowobj: { ...item },
          });
        }
      });
    };
    tileTreeData(treeDept);
    return option;
  }, [treeDept, leftSearchValue]);

  /**
   *  点击搜索
   * @param value
   * @param option
   */
  const onAutoSelectLeft = (value: string, option: any) => {
    // const promise = new Promise((resolve) => {
    const optionId = option?.key;
    const rowObj = option?.itemrowobj;
    const targetNode = loopArray(treeDept); //平铺的树
    let openTreeIds = transltateFn(targetNode, rowObj?.pID);
    updateDispath({
      type: IActionEnum.LEFTAUTO_PARENT,
      payload: true,
    });
    updateDispath({
      type: IActionEnum.LEFTEXPANDED_KEYS,
      payload: openTreeIds,
    });

    setLeftSearchValue(value);
    setTimeout(() => {
      scrollToAnchor(optionId);
    }, 1000);
  };
  // 滚动定位
  const scrollToAnchor = (id: string) => {
    let anchorElement = document.getElementById(id + 'cardLeftDept');
    if (id) {
      anchorElement?.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'start',
      });
    }
  };
  /**
   * 搜索框改变
   * @param e
   */
  const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    setLeftSearchValue(e.target.value);
  };

  /**
   * 渲染树数据
   * @param data
   * @returns
   */
  const orgTreeData = (data: any[]): any[] => {
    let disabled: boolean = false;
    return data?.map((item) => {
      const name = item?.text;
      // +
      // (item?.attributes?.companyName
      //   ? `（${item?.attributes?.companyName}）`
      //   : '');
      const nameLength = name?.length;
      const select = name?.search(leftSearchValue);
      const searchLength = leftSearchValue?.length;
      const afterStr = name?.slice(0, select);
      const selectStr = leftSearchValue;
      const beforeStr = name?.slice(select + searchLength, nameLength);
      const titleTree =
        select > -1 && selectStr ? (
          <Tooltip title={name}>
            <span className={pageStyles['over-flow-hidden']}>
              {afterStr}
              <span style={{ color: '#f50' }}>{selectStr}</span>
              {beforeStr}
            </span>
          </Tooltip>
        ) : (
          <Tooltip title={name}>
            <span className={pageStyles['over-flow-hidden']}>
              {name ?? '--'}
            </span>
          </Tooltip>
        );
      // 判断树节点复选框是否可选
      if (item?.textType == 2 && item?.open == true) {
        disabled = false;
      } else {
        disabled = true;
      }
      return {
        ...item,
        title: (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
            }}
            id={item?.id + 'cardLeftDept'}
          >
            {item?.textType == 0 && <MyIcon type={'icon-bank'} />}
            {item?.textType == 1 && <MyIcon type={'icon-cluster'} />}
            {item?.textType == 2 && <MyIcon type={'icon-icon_lingdaopishi'} />}
            &nbsp;
            {titleTree}
          </div>
        ),
        key: item?.id,
        children:
          item?.children && item?.children?.length > 0
            ? orgTreeData(item?.children)
            : null,
        disabled: disabled,
      };
    });
  };

  /**
   * 保存选中的值
   * @param checkedKeys
   * @param treeNodes
   */
  const onTreeSelect = (checkedKeys: any, treeNodes: any) => {
    // 保存选中的 key
    updateDispath({
      type: IActionEnum.LEFTSELECT_KEYS,
      payload: checkedKeys?.checked,
    });
    // 判断是 选中还是取消
    let isCheck = checkedKeys?.checked?.includes(treeNodes?.node?.id);
    // setTreeSelectKey({
    //   treeKey: treeNodes?.node?.id,
    //   isCheck,
    // })
    if (isCheck) {
      let deptList: any = loopArrayChildren(treeDept); //平铺树,每个节点都有自己的子集
      let getUserList: any = deptList?.filter((item: any) => {
        return item?.id == treeNodes?.node?.id;
      }); //拿到当前点击的 节点
      let userListPayload = commonDeptGetUser(getUserList); //处理成要用的参数格式
      getUserRun(userListPayload); //获取用户
    } else {
      // if (modalType) {
      //   let newCheckKeys: any = joinCheckBoxKeys?.filter((item: any) => { return item != checkID })
      //   let newCheckRows: any = joinCheckBoxRows?.filter((item: any) => { return item?.id != checkID })
      // }
    }
  };

  /**
   *  点击展开关闭树
   */
  const onTreeExpand = useCallback(
    (e, a) => {
      console.log(e, a);
      updateDispath({
        type: IActionEnum.LEFTEXPANDED_KEYS,
        payload: e,
      });
      updateDispath({
        type: IActionEnum.LEFTAUTO_PARENT,
        payload: false,
      });
    },
    [leftSelectKeys],
  );
  console.log('leftSelectKeys====', leftSelectKeys);
  return (
    <Col span={10}>
      <Card
        bordered
        title={
          <>
            <AutoComplete
              style={{ width: '100%' }}
              options={autoOptionLeft}
              notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
              onSelect={onAutoSelectLeft}
            >
              <Input
                suffix={<SearchOutlined />}
                onChange={onInputChange}
                placeholder="请按名称搜索"
                allowClear
              />
            </AutoComplete>
          </>
        }
      >
        <ScrollBarLayout
          style={{
            height: document.body.clientHeight * 0.4,
            padding: '10px 0px',
          }}
        >
          {treeDept && treeDept?.length > 0 ? (
            <Tree
              treeData={orgTreeData(treeDept)}
              blockNode={true}
              checkable={true}
              autoExpandParent={leftAutoExpandParent}
              onCheck={onTreeSelect}
              checkedKeys={leftSelectKeys}
              expandedKeys={leftExpandedKeys}
              onExpand={onTreeExpand}
              checkStrictly={true}
            />
          ) : (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
          )}
        </ScrollBarLayout>
      </Card>
    </Col>
  );
};
export default JoinRemindPeopleLeft;
